<template>
  <div styleaaa="position: relative">
    <!-- <el-button type="primary" @click="dialogTableVisible = true">
      open a Drag Dialog
    </el-button> -->
    <div class="line-div">
      备注名称：
      <el-input
        style="width: 300px"
        v-model="Name"
        placeholder="内部展示用的标记名称，不对外展示"
      ></el-input>
    </div>
    <div class="line-div">
      展示主题：
      <el-input
        style="width: 300px"
        v-model="Title"
        placeholder="广告投放后所展示的主题"
        maxlength="10"
      ></el-input
      ><span>10个字</span>
    </div>
    <div class="line-div">
      展示描述：
      <el-input
        style="width: 600px"
        v-model="Desc"
        placeholder="广告投放后所展示的活动描述"
        maxlength="30"
      ></el-input
      ><span>30个字</span>
    </div>
    <div class="line-div">
      投放时间：
      <el-date-picker
        v-model="dateRange"
        value-format="timestamp"
        type="daterange"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      ></el-date-picker>
    </div>
    <div class="line-div">
       投放时间段： 
        <div class="time-selet" v-if="selectState">
          <div style="margin-bottom:5px">你选择的时间是：</div>
           <div class="time-item">
              <div class="item-day" v-for="item in multTimeRange" :key="item.id">
                   <span>{{item.week}}:</span> <span>{{item.value}}</span>
              </div>
           </div>
        </div>
       <el-button type="primary" plain @click="dialogVisibleDate = true"><i class="el-icon-date" />选择广告投放时间段</el-button> 
    </div>
    <div class="line-div">
      封面视频：
      <div class="video-wraper">
        <div class="video-div" :class="{ seleBg: item.checked }" v-for="(item, indexv) in AdVideo"  v-if="item.checked" >
          <div class="video-list">
            <video :src="item.File"></video>
          </div>
          <div class="video-title">
            <span style="padding: 5px 0; font-size: 14px; font-weight: 600">
              {{ item.Name }}
            </span>
            <span>{{ item.CreatedAt | parseTime }}</span>
          </div>
        </div>
        <el-button plain  type="primary"  @click="handleCreate" ><i class="el-icon-plus" /> 更多视频或上传视频 </el-button>
      </div>
    </div>

    <div class="line-div">
      人群选择：
      <div class="crowd-wraper">
        <div class="Crowd-div" :class="{ seleBg: item.checked }" v-for="item in MdWxCrowd" v-if="item.checked" >
          <div style="padding: 5px 0; font-size: 14px; font-weight: 600">{{ item.Name }} <span style="color:red">({{item.Tot}}人)</span></div>
          <div style="color:#8a8989">{{ item.CreatedAt | parseTime }}</div>
        </div>
        <el-button type="primary" plain  @click="handleAddcrowd"><i class="el-icon-plus" />
          更多人群或添加人群
        </el-button>
      </div>
    </div>

    <div class="line-div">
      落地页选择：
      <div class="pages-wraper">
        <div  class="page-div" :class="{ seleBg: pages.checked }" v-for="pages in MdAdPage" v-if="pages.checked">
          <div class="page-item" v-for="item in pages.JsonStr.list" >
            <div class="page-img" v-if="item.type === 'image' ">
              <img :src="item.src" alt="" />
            </div>
            <div class="page-video" v-if="item.type === 'video'">
              <video :src="item.src" controls></video>
            </div>
            <div class="swiper-box" v-if="item.type == 'swiper'">
                <img :src="item.imgs[0].src" />
            </div>
            <div class="item-btn" v-if="item.type == 'phoneNum'">
              <div :style="{backgroundColor: item.styleObject.backgroundColor, color: item.styleObject.color}">
                {{ item.txt }}
              </div>
            </div>
          </div>
        </div>
        <el-button plain type="primary" @click="handleAddAd" >
          <i class="el-icon-plus" />更多页面或添加页面
        </el-button>
      </div>
    </div>
    
    <div class="line-div">
      <el-button type="primary" @click="submitData">提交</el-button>
    </div>

    <!-- =================视频添加弹出层========================= -->
    <el-dialog :visible.sync="dialogFormVisible"  width="75%">
      <el-form :inline="true" ref="dataForm" :model="temp" label-width="70px"  @submit.native.prevent>
        <el-form-item label="视频标题">
          <el-input v-model="videoname" clearable/>
        </el-form-item>
        <el-form-item label="视频">
          <div style="display:flex;width:100%">
          <div class="add-video-box" style="margin-left:0" >
            <input class="add-video" type="file" @change="changeVideo($event)"/>
            <i class="el-icon-plus" /> 选择视频
          </div>
        </div>   
        </el-form-item > 
        <el-form-item>
          <el-button type="primary"  @click="upVideo">上传<i class="el-icon-upload el-icon--right"></i></el-button>
        </el-form-item>
        <el-form-item>
          <div class="up-video-box"  v-if="videoSrc">   
              <video :src="videoSrc" width="160px" height="90px" controls="controls"></video>
            </div>       
        </el-form-item>                         
      </el-form>
      <div class="form-line"></div>
      <h4>视频列表</h4>
      <div class="video-list-box">
        <div class="video-div" :class="{ seleBg: item.checked }" v-for="(item, indexv) in AdVideo" @click="selectVidoe(item)" >
          <div class="video-list">
            <video :src="item.File"></video>
          </div>
          <div class="video-title">
            <span style="padding: 5px 0; font-size: 14px; font-weight: 600">
              {{ item.Name }}
            </span>
            <span>{{ item.CreatedAt | parseTime }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- ==================================视频添加弹出end============================ -->
    <!-- ==================================人群添加弹出层=============================== -->
    <el-dialog :visible.sync="dialogVisible" width="75%">
      <el-form :inline="true" ref="dataForm" :model="temp" label-width="70px"  @submit.native.prevent>
        <el-form-item label="人群标题">
          <el-input v-model="crowdname" clearable/>
        </el-form-item>
        <el-form-item label="人群号码">
          <div class="add-crowd" >
            <input class="add-video" type="file" @change="changeCrowd($event)" />
            <i class="el-icon-tickets" />添加人群电话号码表
          </div>
        </el-form-item > 
        <el-form-item>
           <el-button type="primary" @click="upExcel">
            <i class="el-icon-folder-add" />
            上传表格
          </el-button>
        </el-form-item>                      
      </el-form>
      <div class="form-line"></div>
      <h4>人群列表</h4>
       <div class="video-list-box">
        <div class="Crowd-div" :class="{ seleBg: item.checked }" v-for="item in MdWxCrowd" @click="seleCrowd(item)" >
          <span>{{ item.Name }} <span style="color:red">({{item.Tot}})</span></span>
          <br />
          <span>{{ item.CreatedAt | parseTime }}</span>
        </div>
       </div>
    </el-dialog>
     <!-- ==================================人群添加弹出层end=============================== -->
     <!-- ==================================广告落地也添加弹出层end=============================== -->
     <el-dialog :visible.sync="dialogVisibleAd" width="75%">
      <el-form :inline="true" ref="dataForm" :model="temp" label-width="70px"  @submit.native.prevent>
        <el-form-item>
           <div class="video-list-add">
           <el-button type="primary" @click="addAdPage(mdid)">新建广告页面</el-button>
        </div>
        </el-form-item>                      
      </el-form>
      <div class="form-line"></div>
      <h4>广告页面列表</h4>
       <div class="page-warper">
        <div class="page-div" :class="{ seleBg: pages.checked }"  v-for="pages in MdAdPage" @click="seleAdPage(pages)">
          <div class="page-div-list">
            <div class="page-list-item" v-for="item in pages.JsonStr.list">
              <div class="page-img" v-if="item.type ==='image'">
                <img :src="item.src"/>
              </div>
              <div class="page-video" v-if="item.type === 'video'">
                <video :src="item.src" controls></video>
              </div>
              <div class="swiper-box" v-if="item.type == 'swiper' && item.imgs.length > 0">
                <img :src="item.imgs[0].src" />
              </div>
              <div class="item-btn" v-if="item.type == 'phoneNum'">
                <div :style="{backgroundColor: item.styleObject.backgroundColor, color: item.styleObject.color}">
                  {{ item.txt }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
   <!-- 日期阶段选择 -->
    <el-dialog title="广告时间段选择" :visible.sync="dialogVisibleDate" width="860px" :before-close="handleClose">      
        <div>
           <drag-weektime
            v-model="multTimeRange"
            :data="weektimeData"
            @on-clear="clearWeektime">
          </drag-weektime>
        </div>      
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleDate = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisibleDate = false">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
function splicing (list) {
  let same
  let i = -1
  let len = list.length
  let arr = []

  if (!len) return
  while (++i < len) {
    const item = list[i]
    if (item.check) {
      if (item.check !== Boolean(same)) {
        arr.push(...['、', item.begin, '~', item.end])
      } else if (arr.length) {
        arr.pop()
        arr.push(item.end)
      }
    }
    same = Boolean(item.check)
  }
  arr.shift()
  return arr.join('')
}
import DragWeektime from "@/components/drag-weektime";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import {
  uploadWxVideo,
  uploadWxCrowd,
  fetchMdCrowdList,
  fetchAdPageList,
  fetchVideoList,
  uploadAd,
} from "@/api/mdlist";
import { parseTime } from "@/utils";
import weektimeData from "@/utils/weektime-data"
const now = new Date();
const start = new Date(
  now.getFullYear(),
  now.getMonth(),
  now.getDate() + 1
).getTime();
const end = now.getTime() + 3600 * 1000 * 24 * 10;

export default {
  directives: { elDragDialog },
  components:{
    DragWeektime
  },
  data() {
    return {
      MdWxCrowd: [], //人群列表
      AdVideo: [], //视频列表
      MdAdPage: [], //广告页面列表
      mdid: "",
      videoname: "", //视频名称
      crowdname: "", //人群名称
      videofile: null,
      corwdFile: null,
      dateRange: [start, end],
      showVideoList: false,
      showCrowdList: false,
      showAdPageList: false,
      Title: "",
      Name: "",
      Desc: "",
      VideoWxId: 0,
      MdAdPageId: 0,
      MdAdWxCrowd: [],
      Stime: 0,
      Etime: 0,
      videoSrc:"",//视频
      selectVideo: { index: 0, id: 0 },
      // =================
       weektimeData: weektimeData,
      dialogTableVisible: false,
      dialogFormVisible: false,//视频添加弹出层控制器
      dialogVisible:false,//人群添加控制器
      dialogVisibleAd:false,//广告落地页弹出层控制器
      dialogVisibleDate:false,//广告阶段选择
       temp: {
        title: '',
      },

      gridData: [
        {
          date: "2016-05-02",
          name: "John Smith",
          address: "No.1518,  Jinshajiang Road, Putuo District",
        },
        {
          date: "2016-05-04",
          name: "John Smith",
          address: "No.1518,  Jinshajiang Road, Putuo District",
        },
        {
          date: "2016-05-01",
          name: "John Smith",
          address: "No.1518,  Jinshajiang Road, Putuo District",
        },
        {
          date: "2016-05-03",
          name: "John Smith",
          address: "No.1518,  Jinshajiang Road, Putuo District",
        },
        {
          date: "2016-05-02",
          name: "John Smith",
          address: "No.1518,  Jinshajiang Road, Putuo District",
        },
        {
          date: "2016-05-04",
          name: "John Smith",
          address: "No.1518,  Jinshajiang Road, Putuo District",
        },
      ],
    };
  },
  computed:{
    multTimeRange(){
      return this.weektimeData.map(item => {
        return {
          id: item.row,
          week: item.value,
          value: splicing(item.child)
        }
      })
    },
    selectState () {
      return this.multTimeRange.some(ret => ret.value)
    },
  },
  created() {
    this.mdid = this.$route.query && this.$route.query.id;
    console.log("99", "---------------mdid:", this.mdid);
    this.getMdCrowdList();
    this.getAdVideoList(); //获取视频
    this.getAdPageList();
    // console.log(this.weektimeData,'ddddddddd');
  },
  methods: {
    //读取视频上传视频
    changeVideo(e) {
      this.videofile = e.target.files[0];
      this.videoSrc = e.target.files[0].name 
    },

    upVideo() {
      let _this = this;
      //提交图片
      let param = new FormData();
      param.append("name", this.videoname);
      console.log(param)
      param.append("public", "public");
      param.append("file", this.videofile, this.videofile.name);
      _this.listLoading = true;
      uploadWxVideo(param, {
        "Content-Type": "multipart/form-data",
        Mdid: _this.mdid,
      }).then((response) => {
        this.listLoading = false;
        if (response.code == 0) {
          _this.AdVideo.unshift(response.data.video);
        }
      });
    },
    /**
     * 读取表格
     */
    changeCrowd(e) {
      this.corwdFile = e.target.files[0];
    },
    /**
     * 人群表格上传
     */
    upExcel() {
      let _this = this;
      //提交数据包
      let param = new FormData();
      param.append("name", this.crowdname);
      param.append("file", this.corwdFile, this.corwdFile.name);
      _this.listLoading = true;
      uploadWxCrowd(param, {
        "Content-Type": "multipart/form-data",
        Mdid: _this.mdid,
      }).then((response) => {
        this.listLoading = false;
        if (response.code == 0) {
          _this.MdWxCrowd.unshift(response.data.crowd);
        }
      });
    },
    addAdPage(mdid) {
      this.$router.push({ name: "cbd-adpage", query: { id: mdid } });
    },

    /**
     * 广告人群
     */
    getMdCrowdList() {
      fetchMdCrowdList("", {
        Mdid: this.mdid,
      }).then((response) => {
        let MdWxCrowd = response.data.list;
        for (let i = 0; i < MdWxCrowd.length; i++) {
          MdWxCrowd[i].checked = false;
        }
        this.MdWxCrowd = MdWxCrowd;
        this.listLoading = false;
      });
    },

    /**
     * 人群选中
     */
    seleCrowd(obj) {
      obj.checked = !obj.checked;
    },

    /**
     * 获取视频
     */
    getAdVideoList() {
      fetchVideoList("", {
        Mdid: this.mdid,
      }).then((response) => {
        let AdVideo = response.data.list;
        for (let i = 0; i < AdVideo.length; i++) {
          AdVideo[i].checked = false;
        }
        this.AdVideo = AdVideo;
        this.listLoading = true;
      });
    },

    /**
     * 视频选中
     */
    selectVidoe(obj) {
      for (let i = 0; i < this.AdVideo.length; i++) {
        this.AdVideo[i].checked = false;
      }
      obj.checked = true;
    },

    /**
     * 获取广告页面
     */
    getAdPageList() {
      fetchAdPageList("", {
        Mdid: this.mdid,
      }).then((response) => {
        let MdAdPage = response.data.list;
        for (let i = 0; i < MdAdPage.length; i++) {
          MdAdPage[i].checked = false;
          MdAdPage[i].JsonStr = JSON.parse(MdAdPage[i].JsonStr);
          console.log(MdAdPage[i].JsonStr.list);
        }
        
         this.MdAdPage = MdAdPage;
      });
    },

    /**
     * 广告页面选中
     */
    seleAdPage(obj) {
      for (let i = 0; i < this.MdAdPage.length; i++) {
        this.MdAdPage[i].checked = false;
      }
      obj.checked = true;
    },

    //提交
    submitData() {
      //获取视频的ID
      let videoid;
      for (let i = 0; i < this.AdVideo.length; i++) {
        if (this.AdVideo[i].checked == true) {
          videoid = this.AdVideo[i].Id;
        }
      }

      //获取选中人群的ID
      let totnum = 0;
      this.MdAdWxCrowd.length = 0;
      for (let i = 0; i < this.MdWxCrowd.length; i++) {
        if (this.MdWxCrowd[i].checked == true) {
          this.MdAdWxCrowd.push(this.MdWxCrowd[i].Id);
          totnum += this.MdWxCrowd[i].Tot;
        }
      }

      //获取广告页面ID
      let pageid;
      for (let i = 0; i < this.MdAdPage.length; i++) {
        if (this.MdAdPage[i].checked == true) {
          pageid = this.MdAdPage[i].Id;
        }
      }
      //获取广告时间段
      let multTimeRange = this.multTimeRange
      let params = {
        Name: this.Name,
        Title: this.Title,
        Desc: this.Desc,
        Stime: parseInt(this.dateRange[0] / 1000),
        Etime: parseInt(this.dateRange[1] / 1000),
        videoid,
        Crowd: this.MdAdWxCrowd,
        pageid,
      };

      //先去查一下余额
      // todo...

      uploadAd(params, {
        Mdid: this.mdid,
      }).then((response) => {
        this.listLoading = false;
        if (response.code == 0) {
          alert(999);
        }
      });

      console.log(params);
    },
    handleDrag() {
      this.$refs.select.blur();
    },
    //显示视频添加弹出层
     handleCreate() {
      this.dialogFormVisible = true
    },
    //显示人群添加弹出层
    handleAddcrowd(){
      this.dialogVisible = true
    },
    //显示添加广告弹出层
    handleAddAd(){
      this.dialogVisibleAd = true
    },
    //关闭阶段选择
    handleClose(){
      this.dialogVisibleDate=false
     
    },
    // 清空时间段
    clearWeektime () {
      this.weektimeData.forEach(item => {
        item.child.forEach(t => {
          this.$set(t, 'check', false)
        })
      })
    },
  },
};
</script>
<style scoped>

.video-list-div,
.crowd-list-div {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 9;
  background: #fff;
  padding: 15px;
}
.line-div {
  margin: 20px 0 15px 20px;
  display: flex;
  align-items: center;
}

.seleBg {
  border: 2px solid #f00808;
}
.video-wraper,
.crowd-wraper,
.pages-wraper{
  display:flex;
  align-items: center;
}

/* .pages-wraper {
  max-width: 1200px;
  min-width: 500px;
  padding: 60px 30px 30px 30px;
  border-radius: 10px;
  position: relative;
  position: relative;
  display: flex;
  flex-wrap: wrap;
} */
.video-div {
  width: 204px;
  height: 164px;
  display: flex;
  flex-direction: column;
  margin: 0 10px 10px 0;
  background-color: #f4f4f4;
  padding: 2px;
}
.video-list {
  width: 200px;
  height: 113px;
}
.video-list video {
  width: 100%;
  height: 100%;
}
.video-title {
  widows: 100%;
  height: 51px;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
  justify-content: center;
  font-size: 12px;
  color: #000;
}
.Crowd-div {
  display: inline-block;
  text-align: center;
  margin: 5px;
  background-color: #f4f4f4;
  padding: 20px;
  font-size: 12px;
  color: #000;
}
.page-div {
  width: 150px;
  display: inline-block;
  margin: 10px 10px 0 0;
  background-color: #f4f4f4;
  padding: 2px;
}
.page-warper {
  width: 100%;
  height:400px;
  overflow:scroll;
  display: flex;
  flex-wrap: wrap;
}
.page-item {
  width: 100%;
}
.page-item .page-img {
  width: 100%;
  display: flex;
}
.page-img img {
  width: 100%;
  height: auto;
}
.video-list-title {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
.video-list-add {
  padding-bottom: 15px;
  width: 100%;
  display: flex;
  align-items: center;
}
.video-list-add > .add-input {
  width: 420px;
  margin-right: 10px;
}
.video-list-box {
  width: 100%;
  max-height: 400px;
  overflow: scroll;
  border: 1px solid #f4f4f4;
  border-radius: 10px;
  padding: 20px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.add-video-box {
  width: 100px;
  height: 36px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #ffff;
  position: relative;
  background-color: #1890ff;
  border: 1px solid #1890ff;
  margin-right: 30px;
}
.add-crowd {
   height: 36px;
   padding: 0 10px;
   border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #ffff;
  position: relative;
  background-color: #1890ff;
  border: 1px solid #1890ff;
}
.add-video {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  width: 80px;
  height: 100%;
}
.page-div-list {
  width: 100%;
}
.page-list-item {
  width: 100%;
  display: flex;
  align-items: center;
}
.page-list-item .page-img {
  width: 100%;
  display: flex;
  align-items: center;
}
.page-list-item .page-img img {
  width: 100%;
}
.page-list-item .swiper-box {
  width: 100%;
  display: flex;
  align-items: center;
}
.swiper-box img {
  width: 100%;
}
.page-list-item .item-btn {
  width: 100%;
  height: 50px;
  background-color: #fff;
  display: flex;
  align-items: center;
  color: #000;
  font-size: 16px;
}
.page-list-item .item-btn > div {
  width: 100%;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 5px;
  font-size: 14px;
}
.page-btn .page-video {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.page-video > video {
  width: 100%;
}
.up-video-box {
  width: 160px;
  height: 90px;
  display: flex;
   align-items: center;
   justify-content: center;
}
.up-video-box video {
  width: 100%;
  height: 100%;
}
.video-img {
   border: 1px solid #ddd;
   height: 90px;
   width: 90px;
  display: flex;
   align-items: center;
   justify-content: center;
}
.form-line {
  width: 100%;
  height: 1px;
  background-color: #f4f4f4;
}
.time-selet {
  min-width: 400px;
  padding: 10px;
  border: 1px solid #dddddd;
  border-radius: 5px;
  font-size: 14px;
  margin-right:10px ;
}
.time-item {
  width: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;
  background-color: #f4f4f4;
  padding: 10px;
  color: #000;
  font-size: 12px;
}
.item-day {
  width: 100%;
  padding: 5px 0;
}
/*  */
</style>
